/*===============================================
*   文件名称：udp_server.c
*   创 建 者：     
*   创建日期：2024年09月19日
*   描    述：
================================================*/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{ 
    //创建数据报套接字
    int sfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(-1 == sfd){
        perror("socket");
        return -1;
    }

    //绑定IP PORT
    struct sockaddr_in saddr;
    saddr.sin_family      = AF_INET;
    saddr.sin_port        = htons(8888);
    saddr.sin_addr.s_addr = inet_addr("0");
    if(-1 == bind(sfd, (void *)&saddr, sizeof saddr)){
        perror("bind");
        return -1;
    }

    char buf[1024], pic_len[5];
    socklen_t len = sizeof saddr;

    int ret;
    int fd = open("img1.png", O_RDONLY);
    if(-1 == fd){
        perror("open");
        return -1;
    }
    while(1){
        if(-1 == recvfrom(sfd, buf, 1024, 0, (void *)&saddr, &len)){
            perror("recvfrom");
            continue;
        }
        if(0 != strncmp(buf, "file", 4)){
            sprintf(pic_len, "no");
            sendto(sfd, pic_len, 5, 0, (void *)&saddr, len);
            continue;
        }
        sprintf(pic_len, "ok");
        sendto(sfd, pic_len, 5, 0, (void *)&saddr, len);

        while(1){
            ret = read(fd, buf, 1024);
            if(-1 == ret){
                sprintf(pic_len, "0");
                sendto(sfd, pic_len, 5, 0, (void *)&saddr, len);
                break;
            }
            sprintf(pic_len, "%d", ret);
            printf("size:%d\n", ret);
            sendto(sfd, pic_len, 5, 0, (void *)&saddr, len);
            if(0 == ret)
                break;
            sendto(sfd, buf, ret, 0, (void *)&saddr, len);
        }
        lseek(fd, 0, SEEK_SET);
    }
    return 0;
} 
